package com.aio.news.category.fragment;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.TextView;

import com.aidi.lib.TAInjectView;
import com.aio.news.R;
import com.aio.news.SwipeBackBaseFragment;
import com.aio.news.home.adapter.LatestAdapter;
import com.aio.news.model.NewsModel;
import com.aio.news.net.HttpUtils.Method;
import com.aio.news.net.HttpUtils.RequestState;

public class CategoryListFragment extends SwipeBackBaseFragment implements
		View.OnClickListener {

	@TAInjectView(id = R.id.back, click = "onClick")
	private View back;
	@TAInjectView(id = R.id.title)
	private TextView mTitle;
	@TAInjectView(id = R.id.listview)
	private ListView mListView;

	RequestState mState = new RequestState("category/list");

	private LatestAdapter mAdapter;

	@Override
	public View initView(LayoutInflater inflater) {
		return inflater.inflate(R.layout.category_list_layout, null);
	}

	@Override
	public List<NameValuePair> getParams(RequestState state) {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("t", ""+getArguments().getInt("type")));
		params.add(new BasicNameValuePair("time", mState.tid));
		params.add(new BasicNameValuePair("limit", "" + LIMIT));
		return params;
	}

	@Override
	public void RequestSuccess(String response, RequestState state) {
		if (!TextUtils.isEmpty(response)) {
			NewsModel model = mGson.fromJsonWithNoException(response,
					NewsModel.class);
			if (model != null && model.items != null && !model.items.isEmpty()) {
				mState.tid = "" + model.items.get(model.items.size() - 1).time;
				mAdapter.addItems(model.items);
			} else {
				mState.isBottom = true;
			}
		}
		mState.isRequestServer = false;
	}

	@Override
	public void RequestFail(String errString, RequestState state) {
		mState.isRequestServer = false;
	}

	AbsListView.OnScrollListener scrollListener = new AbsListView.OnScrollListener() {

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
		}

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			if (firstVisibleItem + visibleItemCount == totalItemCount) {
				getMessage(mState, Method.GET);
			}
		}
	};

	@Override
	public void afterCreated() {
		back.setVisibility(View.VISIBLE);
		mTitle.setText(getArguments().getString("name"));
		mAdapter = new LatestAdapter(this);
		mListView.setAdapter(mAdapter);
		mListView.setOnScrollListener(scrollListener);
		getMessage(mState, Method.GET);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.back:
			back();
			break;

		default:
			break;
		}
	}

}
